package frame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import protocol.DataPackage;
import protocol.JsonPackage;
import thread.SendPackageThread;

public class ChatFrame extends JFrame implements ActionListener{
	private DefaultListModel<String> model;
	private String toName;
	private String loginName;
	private DataPackage pack;
	
//	private ObjectInputStream reader;
//	private ObjectOutputStream writer;
	private BufferedReader reader;
	private BufferedWriter writer;
	private JTextArea chatTa;
	private JLabel loginCoin;
	
	private JMenuBar menuBar;
//	private JList<String> friendTa;
	
	private JTextField sendTf;
	private JButton sendBtn;
	private JButton shakeBtn;
	
	public ChatFrame() {
		this.setSize(600, 500);
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.setLocationRelativeTo(null);
		init();
		addEvent();
		this.setVisible(true);
	}
	public ChatFrame(final String loginName, BufferedReader reader, final BufferedWriter writer) {
		this.toName = "\\";//默认群发
		this.reader = reader;
		this.writer = writer;
		this.pack = null;
		this.loginName = loginName;
		this.setSize(600, 500);
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		init();
		addEvent();
		this.setVisible(true);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e){
				int option = JOptionPane.showConfirmDialog(null, "exit the client?","exit remind", JOptionPane.YES_NO_OPTION);
				
				if(option == JOptionPane.YES_OPTION){
					//准备发送包通知服务器，下线
					DataPackage pack = new DataPackage(loginName, "\\", DataPackage.MessageType.LOGOUT, (loginName + " is logout... "), System.currentTimeMillis());
					try {
//						writer.writeObject(pack);
						writer.write(new JsonPackage(pack).getJsonString() + "\n");
						writer.flush();
					} catch (IOException e1) {
						System.out.println("退出客户端异常");
					}
					return;
				}
			}
		});
	}
	private void init(){
		this.setLayout(new BorderLayout());
		JPanel panLeft=new JPanel(new BorderLayout());
		JPanel panRight=new JPanel(new BorderLayout());
		JPanel panLeftBottom=new JPanel(new BorderLayout());
		JPanel panBtnGroup=new JPanel(new BorderLayout());
		
		JPanel pan = new JPanel(new BorderLayout());
		chatTa=new JTextArea(10,20);
		
		
		ImageIcon imageIcon = new ImageIcon(loginName + ".jpg"); 
		loginCoin = new JLabel(loginName, imageIcon, SwingConstants.CENTER);
		pan.add(loginCoin,BorderLayout.NORTH);
		pan.add(new JScrollPane(chatTa),BorderLayout.CENTER);
		
		//使用特别的JLIST
		model = new DefaultListModel<>();
		JList<String> list1 = new JList<>(model);
		
		String[] ss = {"jordan", "tony", "allen", "joel", "nicole"};
		list1.setPreferredSize(new Dimension(100, 100));
		list1.addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				if(!((JList<String>) e.getSource()).getSelectedValue().equals("在线用户")){
					toName =  ((JList<String>) e.getSource()).getSelectedValue();
					setTopic("talk with " + toName + "...");
				}
			}
		});
		
		menuBar = new JMenuBar();
		JMenu list = new JMenu("好友列表");
		for(String i:ss){
			JMenuItem temp = new JMenuItem(i);
			JMenuItem temp1 = new JMenuItem(i);
			list.add(temp);
		}
		menuBar.add(list);
		setJMenuBar(menuBar);
		
		sendTf=new JTextField();
		sendBtn=new JButton("send");
		shakeBtn=new JButton("shake");
		
		sendTf.setFont(new Font("å®‹ä½“", Font.BOLD, 18));
		sendTf.setForeground(Color.BLACK);
		
		chatTa.setFont(new Font("å®‹ä½“", Font.BOLD, 18));
		chatTa.setForeground(Color.black);
		
		JPanel jpanel = new JPanel();
		JButton allButton = new JButton("All");
		allButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				toName = "\\";
				setTopic("talk to all people online");
			}
		});
		
		shakeBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(toName.equals("\\")){
					chatTa.append(loginName + " send a shake to all people..." );
				}else{
					chatTa.append(loginName + " send a shake to " + toName);
				}
				DataPackage pack = new DataPackage(loginName, toName, DataPackage.MessageType.SHAKE, loginName + " send a shake to you...",System.currentTimeMillis());
				new SendPackageThread(pack, reader, writer).start();
			}
		});
		jpanel.setLayout(new BorderLayout());
		jpanel.add(allButton,BorderLayout.NORTH);
		jpanel.add(list1,BorderLayout.CENTER);
		
		panRight.add(jpanel,BorderLayout.CENTER);
		panLeft.add(pan, BorderLayout.CENTER);
		panLeft.add(panLeftBottom,BorderLayout.SOUTH);
		
		this.add(panLeft,BorderLayout.CENTER);
		this.add(panRight,BorderLayout.EAST);
		
		panBtnGroup.add(shakeBtn,BorderLayout.NORTH);
		panBtnGroup.add(sendBtn,BorderLayout.SOUTH);
		panLeftBottom.add(sendTf,BorderLayout.CENTER);
		panLeftBottom.add(panBtnGroup,BorderLayout.EAST);
	}
	
	private void addEvent(){
		sendBtn.addActionListener(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		String content=sendTf.getText();
		
		sendTf.setText("");
		chatTa.append(loginName + ": " + content +"\n");
		
		pack = new DataPackage(loginName, toName, DataPackage.MessageType.MESSAGE, content, System.currentTimeMillis());			//不选择发送者，默认发给服务器
		//发送包的线程
		new SendPackageThread(pack, reader, writer).start();
	}
	
	public String getLoginName(){
		return loginName;
	}
	
	public JTextArea getChatText(){
		return chatTa;
	}
	public void setChatText(String content){
		chatTa.append(content);
	}
	
	public DataPackage getPackage(){
		return pack;
	}
	public void setTopic(String topic){
		this.setTitle(topic);
	}
	public void shake(){
		int x = this.getLocation().x;
		int y = this.getLocation().y;
		
		for(int i = 0; i < 10; i++){
			try{
				Point endPoint = new Point(x + 10, y + 10);
				this.setLocation(endPoint);
				Thread.sleep(100);
				endPoint = new Point(x - 10, y - 10);
				this.setLocation(endPoint);
				Thread.sleep(100);
			}
			catch(InterruptedException e){
				System.out.println("抖动异常");
			}
		}
	}
	
	public void addModel(String test){
		model.addElement(test);
	}
	public void removeAllModel(){
		model.removeAllElements();
		model.addElement("在线用户");
	}
}
